"use strict"

const { Service } = require('egg')
class TokenService extends Service {

    /**
     * 获取Token
     * @param {object} data 
     * @returns 
     */
    get(data) {
        const { app } = this
        return app.jwt.sign(data,app.config.jwt.secret, {expiresIn:'30d'})
    }

    /**
     * 验证Token
     * @param {string} token 
     * @returns 
     */
    check(token) {
        const { app } = this
        try {
            return app.jwt.verify(token, app.config.jwt.secret)
        } catch (error) {
            return error
        }
    }
    
    /**
     * token 错误英文转中文
     * @param {string} str 
     * @returns 
     */
    message(str) {
        let txt;
        switch (str) {
            case "clockTimestamp must be a number":
                txt = "时钟时间戳必须是一个数字";
                break;
            case "nonce must be a non-empty string":
                txt = "nonce必须是非空字符串";
                break;
            case "jwt must be provided":
                txt = "用户未登录"; //'必须提供令牌';
                break;
            case "jwt must be a string":
                txt = "令牌必须是字符串";
                break;
            case "jwt malformed":
                txt = "令牌格式错误";
                break;
            case "invalid token":
                txt = "无效令牌";
                break;
            case "jwt signature is required":
                txt = "必须提供令牌签名";
                break;
            case "secret or public key must be provided":
                txt = "必须提供秘钥或公钥";
                break;
            case "invalid algorithm":
                txt = "无效的算法";
                break;
            case "invalid signature":
                txt = "无效的签名";
                break;
            case "jwt not active":
                txt = "令牌未激活";
                break;
            case "jwt expired":
                txt = "用户账号登录已过期";
                break;
            default:
                txt = str;
        }
        return txt;
    }
}
module.exports = TokenService